package com.alfayun.fiscalriskanalysis.importer;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alfayun.fiscalriskanalysis.common.HttpBadRequestException;
import com.alfayun.fiscalriskanalysis.common.HttpNotFoundException;
import com.alfayun.fiscalriskanalysis.report.NoSuchReportException;
import com.alfayun.fiscalriskanalysis.report.ReportService;

@RestController
public final class ImporterController {

	private final ImporterService service;
	
	@Autowired
	public ImporterController(ImporterService service) {
		this.service = service;
	}
	
	@Autowired
	private ReportService reportServive;

	@PostMapping("/api/v1/upload")
	public String singleFileUpload(@RequestParam MultipartFile file) throws IOException {
		return service.storeFile(file).toString();
	}
	
	@PutMapping("/import/report/{reportId}")
	public ImportResult importReport(@RequestParam("file") MultipartFile file, @PathVariable int reportId)
			throws IOException, HttpNotFoundException, HttpBadRequestException {
		if (file.isEmpty()) {
			throw HttpBadRequestException.build("Empty file.");
		}

		try {
			return reportServive.importReprot(file.getInputStream(), reportId);
		} catch (NoSuchReportException e) {
			throw HttpNotFoundException.build(e, "报表 [ id: %d ] 不存在。", reportId);
		}
	}
}
